package com.adlotto2.lcdns.activity.ad.request;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.adlotto2.lcdns.R;
import com.adlotto2.lcdns.activity.ad.LottoAdJobChoiceActivity;
import com.adlotto2.lcdns.activity.info.LottoAdAdressListActivity;
import com.adlotto2.lcdns.common.BaseActivity;
import com.adlotto2.lcdns.cronos.http.CNLottoAdApiSet;
import com.adlotto2.lcdns.cronos.http.CNLottoAdApiSetEx;
import com.adlotto2.lcdns.util.BKAddress;
import com.adlotto2.lcdns.util.BKLocationManager;
import com.adlotto2.lcdns.util.CNCronosLog;

public class LottoAdRequestActivity extends BaseActivity implements BKLocationManager.LocationStateListener {
	private String TAG = "LottoAdRequestActivity";
	
	private final int REQUEST_ADDRESS_ACTIVITY = 10000;
	private final int OPTION_JOB = 20000;
	
	private final int CHECK_MODE = 1000;
	private final int REQUEST_MODE = 2000;
	
	private final String BASE_URL = "http://ad.lcdns.kr/server/findManager.asp?ManagerId=";
	private final String RESULT_SUCCESS = "SUCCESS";
	private final String RESULT_FAIL = "FAIL";
	
	private BKLocationManager mLocationManager;
	private TextView mAddressTextView;
	
	private int mCurrentMode = CHECK_MODE;
	
	
	private Context mContext;
	
	private EditText mCompanyName, mRepresentativeName, mPhoneNumber, mAdPart, mDbManager;
	private Button mLocation;
	
	private Button mConfirmButton, mCancelButton;
	
	private String mSido = "", mGugun = "", mDong = "", mAddress = "";
	
	private boolean mIsAddrSelect = false, mIsJobSelected = false;
	
	private String mJobSelectedCount = "", mJobSelectedCodes = "", mJobSelectedNames = "", mDbManagerString;
	
	// 광고부문 선택 라디오 그룹
	private RadioGroup mRadioGroup;
	// 광고부문 선택파트, 1 : 로또기반, 2 : 위치기반
	private int mWhichPart = 1;
	
	// 업종선택 버튼
	private Button mSelectJobButton;
	
	/*LottoAdAdressListActivity*/
	@Override
	protected int onGetContentViewResource() {
		// TODO Auto-generated method stub
		return R.layout.lotto_ad_request_activity;
	}
	
	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		mContext = this;
		mLocationManager = new BKLocationManager(this);
		mLocationManager.setOnLocationStateListener(this);
		
		Button locationBtn = (Button) findViewById(R.id.btn_current_location);
		locationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mLocationManager.requestCurrentLocations();
			}
			
		});
		
		mAddressTextView = (TextView) findViewById(R.id.tv_address);
		
		mCompanyName = (EditText) findViewById(R.id.et_request_company_name);
		mRepresentativeName = (EditText) findViewById(R.id.et_request_representative_name);
		mPhoneNumber = (EditText) findViewById(R.id.et_request_phone_number);
		
//		mPhoneNumber.addTextChangedListener(new TextWatcher() {
//			@Override
//			public void afterTextChanged(Editable s) {
//			}
//
//			@Override
//			public void beforeTextChanged(CharSequence s, int start, int count,	int after) {
//			}
//
//			@Override
//			public void onTextChanged(CharSequence s, int start, int before, int count) {
//				String formattingNumber = PhoneNumberUtils.formatNumber(s.toString());
//				mPhoneNumber.setText((CharSequence) formattingNumber);
//			}
//		});
		
		mPhoneNumber.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
					showAddressListActivity();
				}
				return false;
			}
		});
		
		mLocation = (Button) findViewById(R.id.btn_request_location);
		mLocation.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showAddressListActivity();
			}
		});
		
		mAdPart = (EditText) findViewById(R.id.et_request_ad_part);
		
		mConfirmButton = (Button) findViewById(R.id.btn_request_confirm);
		mCancelButton = (Button) findViewById(R.id.btn_request_cancel);
		
		mConfirmButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(mCompanyName.getText().length() == 0) {
					Toast.makeText(mContext, "상호를 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else if(mRepresentativeName.getText().length() == 0) {
					Toast.makeText(mContext, "대표자 성함을 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else if(mPhoneNumber.getText().length() == 0) {
					Toast.makeText(mContext, "전화번호를 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else if(mLocation.getText().length() == 0) {
					Toast.makeText(mContext, "지역을 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else if(mSelectJobButton.getText().length() == 0) {
					Toast.makeText(mContext, "업종을 선택해 주세요", Toast.LENGTH_SHORT).show();
				} else {
					if(mDbManager.getText().length() == 0) {
						new AlertDialog.Builder(mContext).setTitle(R.string.popup_alert).
						setMessage(R.string.no_recommender_warning).
						setPositiveButton(R.string.btn_title_yes, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								mCurrentMode = REQUEST_MODE;
								mDbManagerString = "";
								hideKeyboard();
								sendAdRequest();
							}
						}).
						setNegativeButton(R.string.btn_title_no, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								mDbManager.requestFocus();
							}
						}).show();
					} else {
						mCurrentMode = CHECK_MODE;
						onRequestData();
						
					}
				}
				
				
				
			}
		});
		
		mCancelButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hideKeyboard();
				goBack();
				
			}
		});
		
		mRadioGroup = (RadioGroup) findViewById(R.id.rg_which_base);
		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch(checkedId) {
					case R.id.rb_lotto_base:
						mWhichPart = 1;
						Toast.makeText(mContext, "로또기반 선택됨", Toast.LENGTH_SHORT).show();
						break;
						
					case R.id.rb_location_base:
						mWhichPart = 2;
						Toast.makeText(mContext, "위치기반 선택됨", Toast.LENGTH_SHORT).show();
						break;
				}
				
			}
		});
		
		mSelectJobButton = (Button) findViewById(R.id.btn_request_ad_job);
		mSelectJobButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Toast.makeText(mContext, "업종버튼 클릭", Toast.LENGTH_SHORT).show();
				
				
				Intent intent = new Intent(mContext, LottoAdJobChoiceActivity.class);
				intent.putExtra("requestMode", String.valueOf(LottoAdJobChoiceActivity.MODE_REQUEST));
				startActivityForResult(intent, OPTION_JOB);
			}
		});
		
		mDbManager = (EditText) findViewById(R.id.et_request_number);
		
	}
	
	private void showAddressListActivity() {
		Intent intent = new Intent(mContext, LottoAdAdressListActivity.class);
		intent.putExtra("isRegistActivity",	false);
		startActivityForResult(intent, REQUEST_ADDRESS_ACTIVITY);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == REQUEST_ADDRESS_ACTIVITY && resultCode == RESULT_OK){
			mIsAddrSelect = true;
			mAddress = data.getStringExtra("address");
			mSido = data.getStringExtra("sido");
			mGugun = data.getStringExtra("gugun");
			mDong = data.getStringExtra("dong");
			mLocation.setText(mAddress);
			
			mRadioGroup.requestFocus();
			hideKeyboard();
//			mAdPart.requestFocus();
//			showKeyboard(mAdPart);
		} else if(requestCode == OPTION_JOB && resultCode == RESULT_OK) {
			// TODO: 업종 선택되어 돌아왔을때 처리!!
			mIsJobSelected = true;
			mJobSelectedCount = data.getStringExtra("selectedJobsCount");
			mJobSelectedCodes = data.getStringExtra("selectedJobsCode");
			mJobSelectedNames = data.getStringExtra("selectedJobs");
			mSelectJobButton.setText(mJobSelectedNames);
			
			if(!CNLottoAdApiSet.isLive()) {
				Toast.makeText(mContext, mJobSelectedCount + ", " + mJobSelectedNames + " 선택됨", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public void showKeyboard(EditText which) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInputFromInputMethod(which.getApplicationWindowToken(), InputMethodManager.SHOW_IMPLICIT);
	}
	
	public void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
	}
	
	public void sendAdRequest() {
		this.onRequestData();
	}
	
	public void goBack() {
		super.onBackPressed();
	}

	@Override
	public void onAsyncPreRequest() {
		super.showLoadingDialog(R.string.requesting, mContext);
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject) {
		super.hideLoadingDialog();
		if(mCurrentMode == CHECK_MODE) {
			String result = RESULT_FAIL;
			try {
				NodeList returnCodeList = xmlObject.getElementsByTagName("rcode");
				
				result = returnCodeList.item(1).getFirstChild().getNodeValue();
			} catch(Exception e) {
				e.printStackTrace();
			}
			
			if(result.equals(RESULT_FAIL)) {
				showFailDialog();
			} else {
				if(result.equals(RESULT_SUCCESS)) {
					mDbManagerString = "AL" + mDbManager.getText().toString();
					mCurrentMode = REQUEST_MODE;
					hideKeyboard();
					sendAdRequest();
				}
			}
		} else {
			showRequestAdSuccessDialog();
		}
		
		
		
		
		
		
	}
	
	public void showRequestAdSuccessDialog() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
		dialog.setTitle(R.string.popup_alert).
		setMessage(R.string.request_ad_success).
		setPositiveButton(R.string.commons_ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				goBack();
			}
		}).show();
	}
	

	@Override
	public void onAsyncCancelRequest() {
		super.hideLoadingDialog();
		Log.e(TAG, "ASYNC CANCEL REQUEST");
	}

	@Override
	public String onGetAsyncRequestUrl() {
		String url = null;

		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		
		if(mCurrentMode == CHECK_MODE) {
			url = BASE_URL + "AL" + mDbManager.getText().toString();
		} else {
			url = MnetGlobalApiSetEx.setRequestAdUrl(mContext, mCompanyName.getText().toString(), mRepresentativeName.getText().toString(), mPhoneNumber.getText().toString(), 
					mDbManagerString, mSido, mGugun, mDong, mWhichPart, mJobSelectedCodes);
		}
		
		Log.d(TAG, "onGetAsyncRequestUrl(url : " + url);
		return url;
	}

	@Override
	public void onAsyncRequestError(int paramInt) {
		// TODO Auto-generated method stub
		super.hideLoadingDialog();
		Log.e(TAG, "REQUEST ERROR");
	}

	@Override
	public void onAsyncDataError(Element paramXMLObject, String paramString) {
		// TODO Auto-generated method stub
		super.hideLoadingDialog();
		Log.e(TAG, "ASYNC DATA ERROR");
	}

	@Override
	public void onLocationGettingtFinished(Location location, BKAddress address) {
		mAddressTextView.setText(address.getFullAddress());
		
	}

	@Override
	public void onLocationGettingError(String reason) {
		// TODO Auto-generated method stub
		
	}
	
	private void showFailDialog() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
		dialog.setTitle(R.string.popup_alert).
		setMessage(R.string.not_valid_recommender_id).
		setPositiveButton(R.string.commons_ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mDbManagerString = "";
				mCurrentMode = REQUEST_MODE;
				sendAdRequest();
			}
		}).
		setNegativeButton(R.string.commons_cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				mDbManager.setText("");
				mDbManager.requestFocus();
			}
		})
		.show();
	}

	

}
